package com.weme.common.dialog

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.weme.common.R
import com.weme.common.base.BaseDialog
import com.weme.common.databinding.DialogPermissingBinding
import com.weme.common.util.*

class PermissingDialog(var myActivity: FragmentActivity, var permissing: List<String>, var callback: () -> Unit) : BaseDialog() {

    private lateinit var binding: DialogPermissingBinding
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        binding = DialogPermissingBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ImmersionBar.with(myActivity).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
        if (permissing.size == 1) {
            val state = AppMkHelper.decodeInt(permissing[0], 0)
            if (state != 3) {// 没有拒绝并不在询问
                binding.tvCancel.setVisible(true)
                binding.tvYes.setVisible(true)
                binding.tvSetting.setVisible(false)
            }else{
                binding.tvSetting.setVisible(true)
                binding.tvCancel.setVisible(false)
                binding.tvYes.setVisible(false)
            }
            binding.tvPermissing.text = getPermission(permissing[0])

            binding.tvYes.setOnClickListener {
                requestPermission(myActivity, callback, permissing[0])
            }
            binding.tvCancel.setOnClickListener {
                dismiss()
            }
            binding.tvSetting.setOnClickListener {
                dismiss()
                XXPermissions.startPermissionActivity(myActivity, permissing[0])
            }
        } else {
            binding.rcvList.visible()
            binding.tvPermissing.gone()
            binding.rcvList.setVerticalLayoutManager()
            binding.rcvList.adapter = permissionAdapter
            permissionAdapter.submitList(permissing.toMutableList())

            binding.tvCancel.gone()
            binding.tvYes.gone() //判断一个或多个权限是否全部授予了
         //   val isDenied = permissing.all { !XXPermissions.isGranted(myActivity, it) }
            var status = 0
            permissing.forEach {
                Log.e("Permissions",AppMkHelper.decodeInt(it, 0).toString()+"/"+it)
                if(AppMkHelper.decodeInt(it, 0) == 3){
                    status = 3
                }
            }



            binding.tvTip.visible()
            binding.tvTitle.text = resources.getString(com.example.resources.R.string.permissing_title1)
            if(status==3){
                binding.tvSetting.visible()
                binding.tvAllow.gone()
                binding.smvAllow.gone()
            }else{
                binding.tvSetting.gone()
                binding.tvAllow.visible()
                binding.smvAllow.visible()
            }

            binding.tvSetting.setOnClickListener {
                XXPermissions.startPermissionActivity(myActivity, permissing)
                dismiss()
            }
            binding.smvAllow.setOnClickListener {
                requestPermission(myActivity, callback, *permissing.toTypedArray())
            }
        }

    }


    private val permissionAdapter = object : BaseQuickAdapter<String, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: String?) {
            item?.let {
                holder.setText(R.id.tvIcon, getPermissionIcon(it))
                holder.setText(R.id.tvPermissing, getPermission(it))
                holder.setTextColor(R.id.tvPermissing, if (XXPermissions.isGranted(context, it)) Color.parseColor("#000000") else Color.parseColor("#4D000000"))
                holder.setVisible(R.id.imSelect, XXPermissions.isGranted(context, it))
            }
        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_permission, parent)
        }


    }

    private fun requestPermission(context: FragmentActivity, callback: () -> Unit, vararg permissing: String) {
        XXPermissions.with(context).permission(permissing).request(object : OnPermissionCallback {
            override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                permissions.forEach {
                    AppMkHelper.encode(it,1)
                }
                if(permissing.size==1){
                    callback.invoke()
                    dismiss()
                    return
                }
                if (allGranted) {
//                    val isDenied = permissing.all { !XXPermissions.isGranted(myActivity, it) }
//                    if(isDenied){
                        callback.invoke()
                 //   }
                    dismiss()
                }
            }

            override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) { // Handle denied permissions
                permissions.forEach { p ->
                    Log.e("Permissions",if (XXPermissions.isDoNotAskAgainPermissions(myActivity, p)) "不再询问"+p else "拒绝"+p)
                    AppMkHelper.encode(p, if (XXPermissions.isDoNotAskAgainPermissions(myActivity, p)) 3 else 2)
                }
                dismiss()
            }
        })
    }

    fun getPermission(permissing: String): String {
        return when (permissing) {
            Permission.WRITE_EXTERNAL_STORAGE -> {
                getString(com.example.resources.R.string.permissing_storage)
            }
            Permission.CAMERA -> {
                getString(com.example.resources.R.string.permissing_camera)
            }
            Permission.READ_MEDIA_AUDIO, Permission.RECORD_AUDIO -> {
                getString(com.example.resources.R.string.permissing_mic)
            }
            Permission.READ_PHONE_STATE -> {
                "电话"
            }
            Permission.BLUETOOTH_CONNECT -> {
                "蓝牙"
            }
            else -> "未知"
        }
    }

    fun getPermissionIcon(permissing: String): String {
        return when (permissing) {
            Permission.WRITE_EXTERNAL_STORAGE -> {
                getString(com.example.resources.R.string.permissing_storage_icon)
            }
            Permission.CAMERA -> {
                getString(com.example.resources.R.string.permissing_camera_icon)
            }
            Permission.READ_MEDIA_AUDIO, Permission.RECORD_AUDIO -> {
                getString(com.example.resources.R.string.permissing_mic_icon)
            }
            Permission.READ_PHONE_STATE -> {
                "电话"
            }
            Permission.BLUETOOTH_CONNECT -> {
                "蓝牙"
            }
            else -> "未知"
        }
    }
}